package com.zqxq.lottery.controller.order;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.zqxq.common.constant.Result;
import com.zqxq.common.enums.CodeEnum;
import com.zqxq.common.utils.BigDecimalUtils;
import com.zqxq.common.utils.DispatcherUtils;
import com.zqxq.common.utils.StrUtils;
import com.zqxq.lottery.common.constant.HuaYangConstant;
import com.zqxq.lottery.entity.enums.LotteryIdEnum;
import com.zqxq.lottery.entity.po.export.ExpertInfoPO;
import com.zqxq.lottery.entity.po.order.FollowOrderPO;
import com.zqxq.lottery.entity.po.order.UserOrderPO;
import com.zqxq.lottery.entity.po.sys.LotteryKindPO;
import com.zqxq.lottery.entity.vo.order.UserOrderVO;
import com.zqxq.lottery.mapper.order.FollowOrderMapper;
import com.zqxq.lottery.mq.Sender;
import com.zqxq.lottery.service.expert.IExpertInfoService;
import com.zqxq.lottery.service.order.IUserOrderService;
import com.zqxq.lottery.entity.bo.order.UserOrderBO;
import com.zqxq.lottery.service.sys.ILotteryHnumService;
import com.zqxq.lottery.service.sys.ISysConfigService;
import com.zqxq.lottery.service.user.IUserFundsService;
import com.zqxq.lottery.util.DateUtil;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 说    明：   用户订单
 * 创 建 人：	一刀·胡
 * 创建时间：	2018/3/16 9:49
 * 修 改 人：
 * 修改日期：
 **/
@RestController
@Slf4j
public class UserOrderController extends OrderBaseController{

    @Autowired
    private IUserOrderService userOrderService;

    @Autowired
    private ILotteryHnumService lotteryHnumService;

    @Autowired
    private Sender sender;

    @Autowired
    private IExpertInfoService expertInfoService;

    @Autowired
    private FollowOrderMapper followOrderMapper;

    @Autowired
    private IUserFundsService userFundsService;

    @Autowired
    private ISysConfigService sysConfigService;

    //分页查询列表
    @PostMapping("/userorder/page")
    public Result page(@RequestBody UserOrderBO search){
        Result rs = new Result();
        try{
            Page page = userOrderService.queryPage(search);
            rs.setData(page);
        }catch(Exception e){
            rs.setCode(CodeEnum.FAIL.getCode());
            rs.setMsg(CodeEnum.FAIL.getMsg());
            log.error("UerOrder Page  Error:",e);
        }
        return rs;
    }

    //app端分页查询
    @PostMapping("/userorder/page/app")
    public Result pageApp(@RequestBody UserOrderBO search){
        Result rs = new Result();
        try{
            long beginTimes = System.currentTimeMillis();
            Wrapper wrapper = new EntityWrapper();
            wrapper.eq("user_id",search.getUserId());

            Page page = userOrderService.queryPageApp(search);
            rs.setData(page);
            long endTimes = System.currentTimeMillis();
            log.info("-------------------getOrderListTiems----------------------->"+(endTimes - beginTimes));
        }catch(Exception e){
            rs.setCode(CodeEnum.FAIL.getCode());
            rs.setMsg(CodeEnum.FAIL.getMsg());
            log.error("UerOrder Page App Error:",e);
        }
        return rs;
    }
    @PostMapping("/userorder/dj/page/app")
    public Result djPageApp(@RequestBody UserOrderBO search){
        Result rs = new Result();
        try{
            rs = userOrderService.queryDJPageApp(search);
        }catch(Exception e){
            rs.setCode(CodeEnum.FAIL.getCode());
            rs.setMsg(CodeEnum.FAIL.getMsg());
            log.error("UerOrder Page App Error:",e);
        }
        return rs;
    }
    //app端分页查询
    @PostMapping("/userorder/getCount")
    public Integer getUserOrderCount(@RequestParam Long userId){
        Integer count = 0;
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("user_id",userId);
        wrapper.in("status","2,3,4,5,6,10");
        count = userOrderService.selectCount(wrapper);
        return count;
    }


    @PostMapping("/userorder/get")
    public Result<UserOrderVO> get(@RequestParam Long id){
        Result rs = new Result();
        try{
            UserOrderVO order = userOrderService.get(id);
            rs.setData(order);
        }catch(Exception e){
            rs.setCode(CodeEnum.FAIL.getCode());
            rs.setMsg(CodeEnum.FAIL.getMsg());
            log.error("UerOrder Get  Error:",e);
        }
        return rs;
    }

    @PostMapping("/userorder/get/h5")
    public Result<UserOrderVO> getH5(@RequestParam Long id){
        Result rs = new Result();
        try{
            UserOrderVO order = userOrderService.getH5(id);
            rs.setData(order);
        }catch(Exception e){
            rs.setCode(CodeEnum.FAIL.getCode());
            rs.setMsg(CodeEnum.FAIL.getMsg());
            log.error("UerOrder Get  Error:",e);
        }
        return rs;
    }

    //保存
    @PostMapping("/userorder/save")
    public Result save(@RequestBody UserOrderVO vo){
        Result rs = new Result();
        try{
            UserOrderVO order = userOrderService.save(vo);
            rs.setData(order);
        }catch(Exception e){
            rs.setCode(CodeEnum.FAIL.getCode());
            rs.setMsg(CodeEnum.FAIL.getMsg());
            log.error("UerOrder Save  Error:",e);
        }
        return rs;
    }

    @PostMapping("/userorder/updateStatus")
    public Result updateStatus(@RequestParam String id, @RequestParam String status){
        Result rs = new Result();
        try{
            if(StrUtils.isEmpty(id)||StrUtils.isEmpty(status))
                return  new Result(CodeEnum.FAIL_100002.getCode(),CodeEnum.FAIL_100002.getMsg());
            UserOrderVO order = new UserOrderVO();
            order.setId(id);
            order.setTicketStatus(status);
            if("1".equals(status))
                order.setTicketShow("1");
            userOrderService.save(order);
            rs.setData(order);
        }catch(Exception e){
            rs.setCode(CodeEnum.FAIL.getCode());
            rs.setMsg(CodeEnum.FAIL.getMsg());
            log.error("UerOrder updateTicketStatus  Error:",e);
        }
        return rs;
    }

    @PostMapping("/userorder/updateUserOrderStatus")
    public Result updateUserOrderStatus(@RequestParam String id, @RequestParam String status){
        Result rs = new Result();
        try{
            if(StrUtils.isEmpty(id)||StrUtils.isEmpty(status))
                return  new Result(CodeEnum.FAIL_100002.getCode(),CodeEnum.FAIL_100002.getMsg());
            UserOrderPO userOrderPO = userOrderService.updateCancel(id,status);
            rs.setData(userOrderPO);
        }catch(Exception e){
            rs.setCode(CodeEnum.FAIL.getCode());
            rs.setMsg(CodeEnum.FAIL.getMsg());
            log.error("UerOrder updateTicketStatus  Error:",e);
        }
        return rs;
    }

    public static void main(String[] args) {
        System.out.println(DateUtil.getHour(new Date()));
    }

    //创建订单
    @PostMapping("/userorder/add")
    public Result addUserOrder(@RequestBody UserOrderVO vo){
        Result rs = new Result();
        try{
            Long lotteryId = DispatcherUtils.parseLong(vo.getLotteryId());
            //校验赛事开放时间
            String match_open_hour_time = sysConfigService.getValueByKey("MATCH_OPEN_HOUR_TIME");
            try {
                if (StringUtils.isNotEmpty(match_open_hour_time)){
                    int hour = DateUtil.getHour(new Date());
                    Map map = JSONObject.parseObject(match_open_hour_time, Map.class);
                    if (hour < Integer.parseInt(map.get("start").toString()) || hour >= Integer.parseInt(map.get("end").toString())){
                        rs.setCode(CodeEnum.FAIL.getCode());
                        rs.setMsg("赛事非开放时间，不能下单");
                        return rs;
                    }
                }
            } catch (Exception e){
                log.error("赛事开放时间校验异常");
            }
            if(lotteryId.equals(LotteryIdEnum.JCZQ.getId()) || lotteryId.equals(LotteryIdEnum.JCZQ_JJ.getId()) || lotteryId.equals(LotteryIdEnum.JCLQ.getId())) {
                UserOrderVO order = userOrderService.insertOrder(vo);
                rs.setData(order);
            }else if(lotteryId.equals(LotteryIdEnum.DJ.getId())){
                rs = userOrderService.insertOrderAndPay(vo);
            }else{
                if(lotteryHnumService.checkLotteryCanSale(lotteryId,vo.getPeriod())) {
                    UserOrderVO order = userOrderService.insertOrder(vo);
                    rs.setData(order);
                }else{
                    rs.setCode(CodeEnum.FAIL.getCode());
                    rs.setMsg("该期竞猜已停售，请重新选号！");
                }
            }
        }catch(Exception e){
            rs.setCode(CodeEnum.FAIL.getCode());
            rs.setMsg(CodeEnum.FAIL.getMsg());
            log.error("UerOrder Insert  Error:",e);
        }
        return rs;
    }

    //竞猜 开票信息保存
    @PostMapping("/orderticket/save")
    public Result saveOrderTickets(@RequestParam String orderId,@RequestParam String ticketUrls){
        Result rs = new Result();
        try{
            userOrderService.saveOrderTickets(orderId,ticketUrls);
        }catch(Exception e){
            rs.setCode(CodeEnum.FAIL.getCode());
            rs.setMsg(CodeEnum.FAIL.getMsg());
            log.error("UerOrder saveOrderTickets  Error:",e);
        }
        return rs;
    }

    //奖金计算
    @PostMapping("/lottery/calc")
    public Result calcLottery(@RequestParam Long lotteryId){
        Result rs = new Result();
        try{
            //userOrderService.updateCalcLottery(lotteryId);
        }catch(Exception e){
            rs.setCode(CodeEnum.FAIL.getCode());
            rs.setMsg(CodeEnum.FAIL.getMsg());
            log.error("Calculate Lottery  Error:",e);
        }
        return rs;
    }
    @PostMapping("/zdCalc")
    public Result zdCalc(){
        Result rs = new Result();
        try{
            userOrderService.updateCalcLottery(21L);
        }catch(Exception e){
            rs.setCode(CodeEnum.FAIL.getCode());
            rs.setMsg(CodeEnum.FAIL.getMsg());
            log.error("Calculate Lottery  Error:",e);
        }
        return rs;
    }


    @PostMapping("/backmoney")
    public Result orderBackMoney(@RequestParam String orderId,@RequestParam String backMoney){
        Result rs = new Result();
        try{
            BigDecimal _backMoney = BigDecimalUtils.getBigDecimal(backMoney);
            boolean flag = userOrderService.updateOrderBackMoney(orderId,_backMoney);
            rs.setData(flag);
        }catch(Exception e){
            rs.setCode(CodeEnum.FAIL.getCode());
            rs.setMsg(CodeEnum.FAIL.getMsg());
            log.error("UerOrder orderBackMoney  Error:",e);
        }
        return rs;
    }

    @PostMapping("/winorder")
    public Result winUserOrder(@RequestParam String orderId,@RequestParam String rewards,@RequestParam String afterTaxs){
        Result rs = new Result();
        try{
            BigDecimal _rewards = BigDecimalUtils.getBigDecimal(rewards);
            BigDecimal _afterTaxs = BigDecimalUtils.getBigDecimal(afterTaxs);
            userOrderService.winUserOrder(orderId,_rewards,_afterTaxs);
        }catch(Exception e){
            rs.setCode(CodeEnum.FAIL.getCode());
            rs.setMsg(CodeEnum.FAIL.getMsg());
            log.error("UerOrder winorder  Error:",e);
        }
        return rs;
    }

    @PostMapping("/ticket/send")
    public Result ticketSend(@RequestParam String orderId){
        Result rs = new Result();
        try{
            //5分钟后调用华阳票状态查询接口
//            sender.send(HuaYangConstant.MQ_HUAYANG_TICKET,orderId,1000*60*5);
        }catch(Exception e){
            rs.setCode(CodeEnum.FAIL.getCode());
            rs.setMsg(CodeEnum.FAIL.getMsg());
            log.error("ticket send  Error:",e);
        }
        return rs;
    }

    @ApiOperation(value = "华阳-出票", notes = "华阳-出票")
    @PostMapping("/userorder/buyTicket")
    public Result buyTicket(@RequestParam Long orderId){
        Result rs = new Result();
        try{
            UserOrderPO order = userOrderService.selectById(orderId);
            if(order.getStatus()==2 && order.getTicket_status()==0){

            }
//                sender.send(HuaYangConstant.MQ_HUAYANG_ORDER_BET,orderId);
            else{
                rs.setCode(CodeEnum.FAIL.getCode());
                rs.setMsg("订单【"+orderId+"】出票失败！");
            }
        }catch(Exception e){
            rs.setCode(CodeEnum.FAIL.getCode());
            rs.setMsg(CodeEnum.FAIL.getMsg());
            log.error("Buy Ticket Error:",e);
        }
        return rs;
    }

    //创建跟单
    @PostMapping("/userorder/follow/add")
    public Result addUserOrder(@RequestParam Long userId,@RequestParam Long orderId,@RequestParam Integer betTimes){
        Result rs = new Result();
        try{
            UserOrderVO order = userOrderService.getH5(orderId);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = sdf.parse(order.getLotteryTime());
            Long closeTime = date.getTime();
            Long currentTime = System.currentTimeMillis();
            FollowOrderPO followOrderPO = new FollowOrderPO();
            followOrderPO.setOrder_id(orderId);
            followOrderPO = followOrderMapper.selectOne(followOrderPO);
            Integer heelMultiple = followOrderPO.getHeel_multiple();
            betTimes = Integer.valueOf(order.getBetTimes());
            if(closeTime<currentTime) {
                rs.setCode(CodeEnum.FAIL.getCode());
                rs.setMsg("比赛已经开始，不能购买！");
                return rs;
            }
            if(betTimes==0){
                rs.setCode(CodeEnum.FAIL.getCode());
                rs.setMsg("起跟倍数不能为0！");
                return rs;
            }
//            if(betTimes<heelMultiple){
//                rs.setCode(CodeEnum.FAIL.getCode());
//                rs.setMsg("该单最低投注"+heelMultiple+"倍！");
//                return rs;
//            }
            if (followOrderPO.getUser_id().equals(userId)) {
                rs.setCode(CodeEnum.FAIL.getCode());
                rs.setMsg("抱歉，不能跟自己的推单！");
                return rs;
            }
            UserOrderVO userOrderVO = userOrderService.insertFollowOrder(userId,order,betTimes);
            rs.setData(userOrderVO);

        }catch(Exception e){
            rs.setCode(CodeEnum.FAIL.getCode());
            rs.setMsg(CodeEnum.FAIL.getMsg());
            log.error("FollowOrder Insert  Error:",e);
        }
        return rs;
    }
    @PostMapping("/userorder/getUserTodayPushOrder")
    public Result getUserTodayPushOrder(@RequestParam Long userId){
        Result rs = new Result();
        try{
            Integer count = userOrderService.getUserTodayPushOrder(userId);
            rs.setData(count);
        }catch(Exception e){
            rs.setCode(CodeEnum.FAIL.getCode());
            rs.setMsg(CodeEnum.FAIL.getMsg());
            log.error("getUserTodayPushOrder  Error:",e);
        }
        return rs;
    }

    @PostMapping("/userorder/getUserTwoDayPushOrder")
    public Result<List<UserOrderVO>> getUserTwoDayPushOrder(@RequestParam Long userId){
        Result rs = new Result();
        try{
            List<UserOrderVO> list = userOrderService.getUserTwoDayPushOrder(userId);
            rs.setData(list);
        }catch(Exception e){
            rs.setCode(CodeEnum.FAIL.getCode());
            rs.setMsg(CodeEnum.FAIL.getMsg());
            log.error("getUserTwoDayPushOrder  Error:",e);
        }
        return rs;
    }

    //支付订单
    @PostMapping("/userorder/pay")
    public Result payUserOrder(Long userId, Long orderId, Long couponId){
        Result rs = new Result();
        try{
            UserOrderVO order = userOrderService.get(orderId);
            if(!String.valueOf(userId).equals(order.getUserId())){
                return new Result(CodeEnum.FAIL.getCode(),"下单用户和订单关联用户不匹配！");
            }
            rs = userFundsService.payOrder(order,couponId);
            if(rs.getCode()==CodeEnum.FAIL.getCode()){
                return rs;
            }
        }catch(Exception e){
            rs.setCode(CodeEnum.FAIL.getCode());
            rs.setMsg(CodeEnum.FAIL.getMsg());
            log.error("UerOrder Pay  Error:",e);
        }
        return rs;
    }
}
